import {Base} from "../../utils/base.js";
class Cart extends Base{
   constructor(){
      super();
      this._storageKeyName = 'cart';
   }
   // 加入购物车
   add(item, counts){
      //获取全部本地缓存数据
      var localStorageData = this._getLocalStorageData();
      //获取某一个缓存数据
      var localStorageProductData = this._isHasThisProduct(item.id, localStorageData);
      //数据不存在
      if(localStorageProductData.index == -1){
         item.counts = counts;
         item.selected = true;
         localStorageData.push(item);
      }else{
         localStorageData[localStorageProductData.index].counts = counts;
      }
      //再次存到缓存
      wx.setStorageSync(this._storageKeyName, localStorageData);
   }
   //获取本地的购物车信息
   _getLocalStorageData(flag){
      var result = wx.getStorageSync(this._storageKeyName);
      if(!result){
         return result = [];
      }else {
         if(flag){
            let arr = [];
            let length = result.length;
            for(let i = 0; i < length; i++){
               if(result[i].selected){
                  arr.push(result[i]);
               }
            }
            result = arr;
         }
         return result;
      }
   }
   //从本地缓存中查找是否有该商品
   _isHasThisProduct(id, localStorageData){
      var item, result={index:-1};
      var length = localStorageData.length;
      for(let i = 0; i <length; i++){
         item = localStorageData[i];
         if (id == item.id){
            result = {
               index: i,
               data: item
            }
            break;
         }
      }
      return result;
   }
   //获取缓存中商品的总数用于购物车显示
   getTotalProductCount(){
      var localStorageData = this._getLocalStorageData();
      var length = localStorageData.length;
      var counts = 0;
      for(let i = 0; i < length; i++){
         counts += localStorageData[i].counts;
      }
      return counts;
   }
   //获取缓存中选中的商品的数量
   _getCartSelectedTotalCounts(flag){
      var data = this._getLocalStorageData();
      let counts = 0;
      var length = data.length;
      for(let i = 0; i < length; i++){
         if(flag) {
            if (data[i].selected){
               counts += data[i].counts;
            }
         }else{
            counts += data[i].counts;
         }
      }
      return counts;
   }
   // 获取点击事件的属性值
   getDataSet(event, key) {
      return event.currentTarget.dataset[key];
   }
   //把新的数据存放到缓存中
   reStorageSync(data){
      wx.setStorageSync(this._storageKeyName, data);
   }
   //支付下单后删除购物车中的数据
   delete(ids){
      if(!(ids instanceof Array)){
         ids = [ids];
      }
      var cartData = this._getLocalStorageData();
      let length = cartData.length;
      for(let i = 0; i < length; i++){
         var hasInfo = this._isHasThisProduct(ids[i], cartData);
         if(hasInfo.index != -1){
            cartData.splice(hasInfo.index, 1);//把缓存中的某一项删除
         }
      }
      wx.setStorageSync(this._storageKeyName, cartData);
   }
}
export {Cart};